//
//  MarketManageVC.swift
//  kxf
//
//  Created by Mac on 2024/3/10.
//

import Foundation
import UIKit
import MCToast

class MarketManageVC : WHBaseViewVC {
    
    var dataSourceArray = NSArray()
    var channelListArray = NSArray()
    
    var merchantType = ""
    var merchatChannle = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendDalaListRequest()
        sendChannelListRequest()
    }
    lazy var topBgImgView : UIImageView = {
        let img = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDHT, height: kFitWidth(194)+getTopSafeAreaHeight()))
        img.setImgLocal(imgName: "market_mange_top_bg")
        
        return img
    }()
    
    lazy var tableView : UITableView = {
        let vi = UITableView.init(frame: CGRect.init(x: 0, y: self.topBgImgView.frame.maxY-kFitWidth(117), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.topBgImgView.frame.maxY-kFitWidth(117))), style: .plain)
        vi.delegate = self
        vi.dataSource = self
        vi.separatorStyle = .none
        vi.backgroundColor = .white
        vi.layer.cornerRadius = kFitWidth(15)
        vi.clipsToBounds = true
        
        vi.register(MarketManageTableViewCell.classForCoder(), forCellReuseIdentifier: "MarketManageTableViewCell")
        
        if #available(iOS 11.0, *) {
            vi.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
        vi.tableFooterView = self.footView
        
        return vi
    }()
    lazy var emptyView : EmptyViewWithBtn = {
        let emptyViewT = EmptyViewWithBtn.init(frame: CGRect.zero)
        emptyViewT.isHidden = true
        emptyViewT.contentLabel.text = "还没有记录~"
        
        return emptyViewT
    }()
    lazy var footView : UIView = {
        let vi = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDHT, height: kFitWidth(100)))
        vi.backgroundColor = .clear
        vi.isUserInteractionEnabled = true
        
        vi.addSubview(self.addBtn)
        
        return vi
    }()
    
    lazy var addBtn : UIButton = {
        let btn = UIButton()
        btn.frame = CGRect.init(x: kFitWidth(31), y: kFitWidth(40), width: kFitWidth(316), height: kFitWidth(48))
        btn.setTitle("新增店铺", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        
        btn.addTarget(self, action: #selector(addBtnAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var choiceTypeAlertVm : ChoiceMercTypeAlertVM = {
        let vm = ChoiceMercTypeAlertVM.init(frame: .zero)
        vm.isHidden = true
        vm.titleLabel.text = "新增商户类型"
        vm.confirmBtn.setTitle("选择商户渠道", for: .normal)
        vm.tapBlock = { [self](typeString)in
            DLLog(message: "\(typeString)")
            
            if typeString == "mini"{
                merchantType = "1"
            }else if typeString == "geti"{
                merchantType = "2"
            }else if typeString == "qiye"{
                merchantType = "0"
            }
            if self.choiceChannelAlertVm.dataArray.count > 0 {
                self.choiceChannelAlertVm.isHidden = false
            }else{
                self.sendAddMarketRequest()
            }
        }
        return vm
    }()
    lazy var choiceChannelAlertVm : ChoiceMercChannelAlertVM = {
        let vm = ChoiceMercChannelAlertVM.init(frame: .zero)
        vm.isHidden = true
        vm.tapBlock = {(channleDict)in
            DLLog(message: "\(channleDict)")
            self.merchatChannle = channleDict["code"]as? String ?? ""
            self.sendAddMarketRequest()
        }
        return vm
    }()
}

extension MarketManageVC{
    @objc func addBtnAction() {
        self.choiceTypeAlertVm.isHidden = false
        
    }
}

extension MarketManageVC{
    func initUI() {
        initNavi(titleStr: "店铺门店管理",isWhite: true)
        self.navigationView.backgroundColor = .clear
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        view.insertSubview(topBgImgView, belowSubview: self.navigationView)
        
        view.addSubview(tableView)
        tableView.addSubview(emptyView)
        emptyView.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: self.tableView.frame.height*0.5)
        
        view.addSubview(choiceTypeAlertVm)
        view.addSubview(choiceChannelAlertVm)
    }
}

extension MarketManageVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        emptyView.isHidden = dataSourceArray.count > 0 ? true : false
        return dataSourceArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MarketManageTableViewCell") as! MarketManageTableViewCell
        let dict = self.dataSourceArray[indexPath.row]as? NSDictionary ?? [:]
        
        cell.updateUI(dict: dict)
        
        cell.changeBlock = {()in
            var nickName = dict["nickname"]as? String ?? ""
            if nickName == ""{
                nickName = dict["username"]as? String ?? ""
            }
            let titleString = "确认切换到【\(nickName)】店铺吗"
            self.presentAlertVc(confirmBtn: "确定", message: "", title: "\(titleString)", cancelBtn: "取消", handler: { action in
                self.sendChangeMarketRequest(memberId: "\(dict["id"]as? Int ?? 0)")
            }, viewController: self)
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kFitWidth(110)
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let vi = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDHT, height: kFitWidth(55)))
        vi.backgroundColor = .white
        
        let titleVm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: kFitWidth(5), width: 0, height: 0))
        vi.addSubview(titleVm)
        titleVm.titleLabel.text = "门店管理"
        
        return vi
    }
//    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        let vi = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDHT, height: kFitWidth(100)))
//        vi.backgroundColor = .white
//
//        vi.addSubview(addBtn)
//
//        return vi
//    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return kFitWidth(55)
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return kFitWidth(100)
    }
}

extension MarketManageVC{
    func sendDalaListRequest() {
        WHNetworkUtil.shareManager().POST(urlString: URL_market_list, parameters: nil) { responseObject in
            DLLog(message: "\(responseObject)")
            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
            self.dataSourceArray = dataObj["list"]as? NSArray ?? []
            self.tableView.reloadData()
        }
    }
    func sendChangeMarketRequest(memberId:String){
        WHNetworkUtil.shareManager().POST(urlString: "\(URL_change_market)?memberId=\(memberId)", parameters: nil,isNeedToast: true,vc: self) { responseObject in
            let dataObj = responseObject["data"] as? NSDictionary ?? [:]
            UserDefaults.standard.setValue("\(dataObj["identity"] ?? "")", forKey: whIdentity)
            UserDefaults.standard.setValue("\(dataObj["tokenHead"] ?? "")", forKey: whTokenHead)
            UserDefaults.standard.setValue("\(dataObj["token"] ?? "")", forKey: whToken)
            UserDefaults.standard.setValue("\(dataObj["tokenHead"] ?? "")\(dataObj["token"] ?? "")", forKey: Authorization)
            
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let newRootVC = LLTabBarViewController()
            appDelegate.switchRootViewController(to: newRootVC)
        }
    }
    func sendAddMarketRequest() {
        let param = ["merchantType":"\(self.merchantType)",
                     "channel":"\(self.merchatChannle)"]
        WHNetworkUtil.shareManager().POST(urlString: URL_add_market, parameters: param as [String :AnyObject],isNeedToast: true,vc: self) { responseObject in
            MCToast.mc_text("店铺新增成功")
            self.sendDalaListRequest()
        }
    }
    func sendChannelListRequest() {
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_channel_list, parameters: nil) { responseObject in
            DLLog(message: "\(responseObject)")
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.choiceChannelAlertVm.updateUI(array: dataArr)
        }
    }
}
